package com.example.social.screen

import android.Manifest
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.ElevatedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.content.ContextCompat
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import coil.compose.rememberAsyncImagePainter
import com.example.social.R
import com.example.social.navigation.Routes
import com.example.social.viewmodel.AuthViewModel

@Composable
fun Register(navHostController: NavHostController) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(24.dp),
        horizontalAlignment = Alignment.CenterHorizontally, //水平居中
        verticalArrangement = Arrangement.Center  //垂直居中
    ) {

        //@Compose Data

        var email by remember {
            mutableStateOf("")
        }
        var nickname by remember {
            mutableStateOf("")
        }
        var userName by remember {
            mutableStateOf("")
        }
        var bio by remember {
            mutableStateOf("")
        }
        var password by remember {
            mutableStateOf("")
        }

        var imageUri by remember {
            mutableStateOf<Uri?>(null)
        }

        val authViewModel: AuthViewModel = viewModel()

        val isErrorShown by authViewModel.isErrorShown.observeAsState(false)

        val resultCode by authViewModel.registerState.observeAsState(null)

        val error by authViewModel.error.observeAsState()

        val permissionToRequest = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            Manifest.permission.READ_MEDIA_IMAGES
        } else Manifest.permission.READ_EXTERNAL_STORAGE

        val context = LocalContext.current

        val launcher =
            rememberLauncherForActivityResult(contract = ActivityResultContracts.GetContent()) { uri: Uri? ->
                imageUri = uri
            }

        val permissionLauncher = rememberLauncherForActivityResult(
            contract = ActivityResultContracts.RequestPermission()
        ) { isGranted: Boolean ->
            if (isGranted) {

            }else{

            }
        }
        //监听状态
        LaunchedEffect(resultCode, isErrorShown, error) {
            if (!isErrorShown && error != null) {
                if (resultCode == 0) {
                    Toast.makeText(context, "注册成功", Toast.LENGTH_SHORT).show()
                    navHostController.navigate(Routes.Login.routes) {
                        popUpTo(navHostController.graph.startDestinationId)
                        launchSingleTop = true
                    }
                } else {
                    // 显示错误消息
                    val errorMessage = error!!.ifBlank { "注册失败，请重试" }
                    Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show()
                }
                authViewModel.markErrorAsShown() // 标记错误信息已经显示
            }
        }

        //@Compose UI

        Text(
            text = "Register Here",
            style = TextStyle(
                fontWeight = FontWeight.ExtraBold,
                fontSize = 24.sp
            )
        )
        Image(
            painter = if (imageUri == null) painterResource(id = R.drawable.person) else rememberAsyncImagePainter(
                model = imageUri
            ),
            contentDescription = "person",
            modifier = Modifier
                .size(95.dp)
                .clip(CircleShape)
                .background(Color.Gray)
                .clickable {
                    val isGranted = ContextCompat.checkSelfPermission(
                        context, permissionToRequest
                    ) == PackageManager.PERMISSION_GRANTED

                    if (isGranted) {
                        launcher.launch("image/*")
                    } else {
                        permissionLauncher.launch(permissionToRequest)
                    }
                },
            contentScale = ContentScale.Crop
        )

        Box(modifier = Modifier.height(25.dp))

        OutlinedTextField(
            value = nickname,
            onValueChange = { nickname = it },
            label = {
                Text(text = "昵称")
            }, keyboardOptions = KeyboardOptions(
                keyboardType = KeyboardType.Text // 点击输入框时自动弹出专门用于电子邮件输入的键盘
            ),
            singleLine = true,//支持单行输入，不会自动换行
            modifier = Modifier.fillMaxWidth()
        )
        OutlinedTextField(
            value = userName,
            onValueChange = { userName = it },
            label = {
                Text(text = "用户名")
            }, keyboardOptions = KeyboardOptions(
                keyboardType = KeyboardType.Text // 点击输入框时自动弹出专门用于电子邮件输入的键盘
            ),
            singleLine = true,//支持单行输入，不会自动换行
            modifier = Modifier.fillMaxWidth()
        )
        OutlinedTextField(
            value = bio,
            onValueChange = { bio = it },
            label = {
                Text(text = "个人简介")
            }, keyboardOptions = KeyboardOptions(
                keyboardType = KeyboardType.Email // 点击输入框时自动弹出专门用于电子邮件输入的键盘
            ),
            singleLine = true,//支持单行输入，不会自动换行
            modifier = Modifier.fillMaxWidth()
        )
        OutlinedTextField(
            value = email,
            onValueChange = { email = it },
            label = {
                Text(text = "邮箱")
            }, keyboardOptions = KeyboardOptions(
                keyboardType = KeyboardType.Email // 点击输入框时自动弹出专门用于电子邮件输入的键盘
            ),
            singleLine = true,//支持单行输入，不会自动换行
            modifier = Modifier.fillMaxWidth()
        )
        //密码
        OutlinedTextField(
            value = password,
            onValueChange = { password = it },
            label = {
                Text(text = "密码")
            }, keyboardOptions = KeyboardOptions(
                keyboardType = KeyboardType.Password // 点击输入框时自动弹出专门用于密码输入的键盘
            ),
            singleLine = true,
            modifier = Modifier.fillMaxWidth()
        )
        Box(modifier = Modifier.height(30.dp))
        //注册
        ElevatedButton(
            onClick = {
                //注册校验
                if (email.isEmpty() || userName.isEmpty() || bio.isEmpty() || password.isEmpty()) {
                    Toast.makeText(context, "请填写空白部分!", Toast.LENGTH_SHORT).show()
                }
                if (userName.length<5){
                    Toast.makeText(context, "用户名太短!", Toast.LENGTH_SHORT).show()
                }
                if ((password.length < 8)) {
                    Toast.makeText(context, "密码太短!", Toast.LENGTH_SHORT).show()
                }
                if (imageUri == null) {
                    Toast.makeText(context, "请添加用户照片", Toast.LENGTH_SHORT).show()
                }
                try {
                    authViewModel.register(email = email,password = password, nickName = nickname, bio =  bio, userName = userName,imageUri = imageUri!!,context)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            },
            modifier = Modifier.fillMaxWidth()
        ) {
            Text(
                text = "注册",
                style = TextStyle(
                    fontWeight = FontWeight.Bold,
                    fontSize = 24.sp
                ),
                modifier = Modifier.padding(vertical = 6.dp) //垂直方向的内边距 6.dp
            )
        }
        //去登录
        TextButton(
            onClick = {
                navHostController.navigate(Routes.Login.routes) {
                    popUpTo(navHostController.graph.startDestinationId) //出栈
                    launchSingleTop = true //复用现有实例
                }
            },
            modifier = Modifier.fillMaxWidth()
        ) {
            Text(
                text = "已经注册? 去登录",
                style = TextStyle(
                    fontWeight = FontWeight.Bold,
                    fontSize = 16.sp
                )
            )
        }
    }
}


@Composable
@Preview(showBackground = true)
fun RegisterPreview() {
    val navController = rememberNavController()
    Register(navController)
}
